#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
#include<vector>
#include<queue>
using namespace std;
class Solution {
    int m, n;
    int dx[4] = { 0,0,1,-1 };
    int dy[4] = { 1,-1,0,0 };
    bool as[301][301];
    int ret = 0;
public:
    int numIslands(vector<vector<char>>& grid) {
        m = grid.size();
        n = grid[0].size();
        for (int i = 0; i < m; i++)
        {
            for (int j = 0; j < n; j++)
            {
                if (grid[i][j] == '1' && !as[i][j])
                {
                    bfs(grid, i, j);
                    ret++;
                }
            }
        }
        return ret;
    }
    void bfs(vector<vector<char>>& grid, int i, int j)
    {
        as[i][j] = true;
        queue<pair<int, int>> aq;
        aq.push({ i,j });
        while (aq.size())
        {
            auto [a, b] = aq.front();
            aq.pop();
            for (int i = 0; i < 4; i++)
            {
                int x = a + dx[i];
                int y = b + dy[i];
                if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == '1' && !as[x][y])
                {
                    aq.push({ x,y });
                    as[x][y] = true;
                }
            }
        }
    }

};